package com.zzty.txj.controller;

import com.zzty.txj.entity.Daily;
import com.zzty.txj.entity.DoDaily;
import com.zzty.txj.entity.User;
import com.zzty.txj.entity.WxConfigInfo;
import com.zzty.txj.service.DpostService;
import com.zzty.txj.service.PostService;
import com.zzty.txj.util.Sha1Util;
import com.zzty.txj.util.WechatUtil;
import com.zzty.txj.util.WeiChatUtil;
import net.sf.json.JSONObject;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.GetMethod;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;

@Controller
@RequestMapping("/page")
public class PageController {
    private static final org.slf4j.Logger logger = LoggerFactory.getLogger(PageController.class);

    private static String ticketUrl = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=";

    @RequestMapping("/login")
    public String login(HttpServletRequest request, HttpServletResponse response, ModelMap model) throws IOException {

        logger.info("============================================");
        String code = request.getParameter("code");

        String openId = WechatUtil.getOpenId(code);


        response.sendRedirect("/html/login.html");
        return "login";
    }


    @Autowired
    PostService postService;
    @Autowired
    DpostService dpostService;

    @RequestMapping("/card")
    public String myPage(HttpServletRequest request, HttpServletResponse response, ModelMap model) throws Exception {


        String code = request.getParameter("code");

        String openId = WeiChatUtil.getOpenId(code);
        logger.info(openId);
        HttpSession session = request.getSession();
        session.setAttribute("openId", openId);
        logger.warn(openId);

        String param = request.getQueryString();

        String url = request.getServletPath();//获取请求路径（不带参数）
        if (param != null) {
            url = url + "?" + param;//组合成完整请求URL
        }
        String projectnameP = request.getContextPath();
        String projectName = projectnameP.substring(projectnameP.lastIndexOf('/') + 1, projectnameP.length());  //获取工程名,如testW
        if (!"".equals(projectName)) {
            projectName = "/" + projectName;
        }
        String port = String.valueOf(request.getServerPort());//获取端口号
        if (!"80".equals(port)) {//不是80端口时需加端口号
            port = ":" + port;
        } else {
            port = "";
        }
        String strBackUrl = "http://" + request.getServerName() + port + projectName + url;


//		String code=req.getParameter("code");
//		String openId= WeiChatUtil.getOpenId(code);
        String nonce_str = UUID.randomUUID().toString().replaceAll("-", "");
        SortedMap<String, String> finalpackage = new TreeMap<String, String>();
        String timestamp = Sha1Util.getTimeStamp();
        finalpackage.put("timestamp", timestamp);
        finalpackage.put("noncestr", nonce_str);
        String ticket = WeiChatUtil.getjsApiTicket(ticketUrl, WeiChatUtil.getAccessToken());
        finalpackage.put("jsapi_ticket", ticket);
        finalpackage.put("url", strBackUrl);

        String signature = Sha1Util.createSHA1Sign(finalpackage);
//		model.addAttribute("timestamp ",timestamp);


        WxConfigInfo wxConfigInfo = new WxConfigInfo();
        wxConfigInfo.setNonceStr(nonce_str);
        wxConfigInfo.setSignature(signature);
        wxConfigInfo.setTimeStamp(timestamp);
        request.getSession().setAttribute("wxConfigInfoMap", wxConfigInfo);
        request.getSession().setAttribute("code", code);


        String result="";
        Date day=new Date();
        SimpleDateFormat df = new SimpleDateFormat("HH:mm:ss");
        String date=String.valueOf(df.format(day));

        SimpleDateFormat df1 = new SimpleDateFormat("yyyy-MM-dd");
        String date1=String.valueOf(df1.format(day));
        logger.info("openId"+openId);
        User user=new User();
        user.setOpenId(openId);
        logger.info(user.toString());
        Daily daily1=new Daily();

        Daily daily=new Daily();
        User user1=dpostService.getUser(user);
        if(null==user1){
            return "user";
        }else{
            logger.info(user1.getName());
            String dailyName=postService.getName(user1.getId());
            System.out.println("dailyName"+dailyName);
            dailyName=dailyName.replaceAll(",","");
            DoDaily doDaily=new DoDaily();
            doDaily.setDate(date1);
            doDaily.setUserId(user1.getId());

            List<DoDaily>doDailies=dpostService.getDoDaily(doDaily);
            for(int i=0;i<doDailies.size();i++){
                String name=postService.getDailyName(doDailies.get(i).getDailyId());
                daily=dpostService.getDaily(doDailies.get(i).getDailyId());
                if(date.compareTo(daily.getStartTime())>0&&date.compareTo(daily.getStopTime())<0){

                    daily1.setId(daily.getId());
                    result=name;
                    if(date.compareTo(dpostService.getDaily(6).getStartTime())>0&&date.compareTo(dpostService.getDaily(6).getStopTime())<0){
                        for(int j=0;j<doDailies.size();j++){

                            daily1.setId(6);

                            if(doDailies.get(j).getDailyId()==5&&doDailies.get(j).getResult()==1){
                                result=name;
                                break;
                            }else{
                                result="午睡没有打卡";
                            }
                        }
                    }
                    break;
                }else{

                    result="chaoshi";
                }
            }


            daily1.setName(result);
            logger.info("dailyId"+daily.toString());

            if(null==daily1.getId())
            {
                return "map2";
            }
            if(8==daily1.getId()){
                return "map3";
            }else{
                return "map2";
            }
        }
    }

    @RequestMapping("/user")
    public String user(HttpServletRequest request) throws Exception {

        String param = request.getQueryString();

        String url = request.getServletPath();//获取请求路径（不带参数）
        if(param!=null){
            url = url+"?"+param;//组合成完整请求URL
        }
        String projectnameP = request.getContextPath();
        String projectName = projectnameP.substring(projectnameP.lastIndexOf('/')+1,projectnameP.length());  //获取工程名,如testW
        if(!"".equals(projectName)){
            projectName ="/"+projectName;
        }
        String port = String.valueOf(request.getServerPort());//获取端口号
        if(!"80".equals(port)){//不是80端口时需加端口号
            port = ":"+port;
        }else{
            port = "";
        }
        String strBackUrl = "http://" + request.getServerName()+port+projectName+url;


        String code=request.getParameter("code");
        String openId= WeiChatUtil.getOpenId(code);

        request.getSession().setAttribute("openId",openId);

        String nonce_str = UUID.randomUUID().toString().replaceAll("-", "");
        SortedMap<String, String> finalpackage = new TreeMap<String, String>();
        String timestamp = Sha1Util.getTimeStamp();
        finalpackage.put("timestamp", timestamp);
        finalpackage.put("noncestr", nonce_str);
        String ticket = WeiChatUtil.getjsApiTicket(ticketUrl, WeiChatUtil.getAccessToken());
        finalpackage.put("jsapi_ticket", ticket);
        finalpackage.put("url", strBackUrl);

        String signature = Sha1Util.createSHA1Sign(finalpackage);
//		model.addAttribute("timestamp ",timestamp);



        WxConfigInfo wxConfigInfo =new WxConfigInfo();
        wxConfigInfo.setNonceStr(nonce_str);
        wxConfigInfo.setSignature(signature);
        wxConfigInfo.setTimeStamp(timestamp);
        request.getSession().setAttribute("wxConfigInfoMap",wxConfigInfo);
        return "user";
    }

    @RequestMapping("/ranking")
    public String ranking(HttpServletRequest request) throws Exception{

        String param = request.getQueryString();

        String url = request.getServletPath();//获取请求路径（不带参数）
        if(param!=null){
            url = url+"?"+param;//组合成完整请求URL
        }
        String projectnameP = request.getContextPath();
        String projectName = projectnameP.substring(projectnameP.lastIndexOf('/')+1,projectnameP.length());  //获取工程名,如testW
        if(!"".equals(projectName)){
            projectName ="/"+projectName;
        }
        String port = String.valueOf(request.getServerPort());//获取端口号
        if(!"80".equals(port)){//不是80端口时需加端口号
            port = ":"+port;
        }else{
            port = "";
        }
        String strBackUrl = "http://" + request.getServerName()+port+projectName+url;


        String code=request.getParameter("code");
        String openId= WeiChatUtil.getOpenId(code);

        request.getSession().setAttribute("openId",openId);

        String nonce_str = UUID.randomUUID().toString().replaceAll("-", "");
        SortedMap<String, String> finalpackage = new TreeMap<String, String>();
        String timestamp = Sha1Util.getTimeStamp();
        finalpackage.put("timestamp", timestamp);
        finalpackage.put("noncestr", nonce_str);
        String ticket = WeiChatUtil.getjsApiTicket(ticketUrl, WeiChatUtil.getAccessToken());
        finalpackage.put("jsapi_ticket", ticket);
        finalpackage.put("url", strBackUrl);

        String signature = Sha1Util.createSHA1Sign(finalpackage);
//		model.addAttribute("timestamp ",timestamp);



        WxConfigInfo wxConfigInfo =new WxConfigInfo();
        wxConfigInfo.setNonceStr(nonce_str);
        wxConfigInfo.setSignature(signature);
        wxConfigInfo.setTimeStamp(timestamp);
        request.getSession().setAttribute("wxConfigInfoMap",wxConfigInfo);
        return "ranking";
    }

    @RequestMapping("/zh1")
    public String zh1(HttpServletRequest request,HttpServletResponse response, ModelMap model)throws  Exception{
        return "car";
    }
//    @RequestMapping("/select")
//    public String select(HttpServletRequest request,HttpServletResponse response, ModelMap model)throws  Exception{
//       System.out.println("1111111");
//
//        return "select";
//    }
    @RequestMapping("/record")
    public String select(HttpServletRequest request,HttpServletResponse response, ModelMap model)throws  Exception{

        String code=request.getParameter("code");

        String openId=WechatUtil.getOpenId(code);

        HttpSession session = request.getSession();
        session.setAttribute("openId", openId);
        return "record";
    }
    @RequestMapping("/route")
    public String route(HttpServletRequest request,HttpServletResponse response, ModelMap model)throws  Exception{
        return "route";
    }
    public static JSONObject getWechatUserInfo(String openId, String token){
        String url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token="+token+"&openid="+openId;
        JSONObject result=null;
        HttpClient client = new HttpClient();
        GetMethod get = new GetMethod(url);
        try {
            client.executeMethod(get);
            String returnJson=get.getResponseBodyAsString();
            returnJson = new String(returnJson.getBytes("ISO8859_1"),"UTF-8");
            result = JSONObject.fromObject(returnJson);

            if(result.containsKey("nickname"))
                return result;
            else
                return result;
        }catch (Exception e) {}

        return result;
    }

}
